package com.tuanzi.loan.business.analyzer;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

import javax.annotation.PostConstruct;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.common.collect.Maps;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.tuanzi.loan.business.service.system.DictionaryService;
import com.tuanzi.loan.core.util.GsonUtils;
import com.tuanzi.loan.vo.view.family.UserValidateView;

import lombok.extern.slf4j.Slf4j;

/**
 * @author Ray 2017/11/01
 */
@Slf4j
@Component
public class BaiduJRAnalyzer {

	@Autowired
	private DictionaryService dictionaryService;

	private Map<String /* value */, String /* name */> dictionaries = Maps.newHashMap();

	@PostConstruct
	private void init() {
		dictionaries = dictionaryService.listMapByCode("BAIDU_JR_REASON_CODE");
	}

	/**
	 * 根据百度金融JSON构造VO对象
	 *
	 * @param json
	 *            百度金融API返回结果
	 * @return UserValidateView.BaiduJR
	 */
	public UserValidateView.BaiduJR analyse(String json) {
		if (StringUtils.isBlank(json)) {
			return null;
		}
		try {
			UserValidateView.BaiduJR baiduJR = new UserValidateView.BaiduJR();

			JsonObject root = new JsonParser().parse(json).getAsJsonObject();
			JsonObject result = root.get("result").getAsJsonObject();

			String jsonBlackDetails = GsonUtils.getAsString(result, "blackDetails").replace("\\\\", "");

			if (StringUtils.isBlank(jsonBlackDetails)) {
				return baiduJR;
			}

			JsonObject blackDetails = new JsonParser().parse(jsonBlackDetails).getAsJsonObject();
			baiduJR.setBlackLevel(GsonUtils.getAsString(result, "blackLevel"));

			List<UserValidateView.BaiduJRResult> results = Stream.of(StringUtils.split(GsonUtils.getAsString(result, "blackReason"), ":")).map(x -> {

				if (blackDetails.isJsonNull() || blackDetails.get(x) == null || blackDetails.get(x).isJsonNull()) {
					return new ArrayList<UserValidateView.BaiduJRResult>();
				}

				JsonArray blackDetailArray = blackDetails.get(x).getAsJsonArray();
				return StreamSupport.stream(blackDetailArray.spliterator(), false).map(y -> {

					UserValidateView.BaiduJRResult baiduJRResult = new UserValidateView.BaiduJRResult();
					baiduJRResult.setBlackReason(dictionaries.get(x));
					baiduJRResult.setBlackDetail(structureBlackDetail(x, y));
					return baiduJRResult;

				}).collect(Collectors.toList());

			}).flatMap(x -> x.stream()).collect(Collectors.toList());
			baiduJR.setResults(results);
			return baiduJR;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return null;
	}

	public String getBlackLevel(String json) {
		if (StringUtils.isEmpty(json)) {
			return StringUtils.EMPTY;
		}
		try {
			JsonObject root = new JsonParser().parse(json).getAsJsonObject();
			return GsonUtils.getAsString(root.get("result").getAsJsonObject(), "blackLevel");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return StringUtils.EMPTY;
	}

	private String structureBlackDetail(String reasonCode, JsonElement jsonElement) {
		JsonObject detail = jsonElement.getAsJsonObject();
		switch (reasonCode) {
		case "C06BT020": {
			String duty = "执行义务 : " + GsonUtils.getAsString(detail, "duty");
			String performance = "执行情况 : " + GsonUtils.getAsString(detail, "performance");
			String publishDate = "公开日期 : " + GsonUtils.getAsString(detail, "publishDate");
			String caseNo = "案件编号 : " + GsonUtils.getAsString(detail, "case_no");
			String disruptTypeName = "违反条例 : " + GsonUtils.getAsString(detail, "disruptTypeName");
			return StringUtils.join(new Object[] { duty, performance, publishDate, caseNo, disruptTypeName }, " </br> ");
		}
		case "C06BT021": {
			String taxpayerName = "税务主体 : " + GsonUtils.getAsString(detail, "taxpayer_name");
			String infoSource = "公开机构 : " + GsonUtils.getAsString(detail, "info_source");
			String majorFact = "主要原因 : " + GsonUtils.getAsString(detail, "major_fact");
			return StringUtils.join(new Object[] { taxpayerName, infoSource, majorFact }, " | ");
		}
		case "C06BT022": {
			String executeCourt = "执行法院 : " + GsonUtils.getAsString(detail, "execute_court");
			String adjudicateNo = "处罚编号 : " + GsonUtils.getAsString(detail, "adjudicate_no");
			String freezeAmount = "冻结金额 : " + GsonUtils.getAsString(detail, "freeze_amount");
			String pubDate = "处罚公开时间 : " + GsonUtils.getAsString(detail, "pub_date");
			String corpName = "合作企业名称 : " + GsonUtils.getAsString(detail, "corp_name");
			return StringUtils.join(new Object[] { executeCourt, adjudicateNo, freezeAmount, pubDate, corpName }, " </br> ");
		}
		case "C06BT023": {
			String punishmentNo = "处罚编号 : " + GsonUtils.getAsString(detail, "punishment_no");
			String causeOfAction = "执法原因 : " + GsonUtils.getAsString(detail, "cause_of_action");
			String handleOrgName = "处罚部门 : " + GsonUtils.getAsString(detail, "handle_org_name");
			String pubDate = "公示日期 : " + GsonUtils.getAsString(detail, "pub_date");
			String punishmentContent = "处罚内容 : " + GsonUtils.getAsString(detail, "punishment_content");
			return StringUtils.join(new Object[] { punishmentNo, causeOfAction, handleOrgName, pubDate, punishmentContent }, " </br> ");
		}
		case "C06BT024": {
			String regDate = "注册时间 : " + GsonUtils.getAsString(detail, "reg_date");
			String caseNo = "案件编号 : " + GsonUtils.getAsString(detail, "case_no");
			String court = "判决法院 : " + GsonUtils.getAsString(detail, "court");
			String exeMoney = "执行金额 : " + GsonUtils.getAsString(detail, "exe_money");
			return StringUtils.join(new Object[] { regDate, caseNo, court, exeMoney }, " </br> ");
		}
		case "C06BT025": {
			String cfWsh = "行政处罚决定书文号 : " + GsonUtils.getAsString(detail, "cf_wsh");
			String cfCfmc = "处罚名称 : " + GsonUtils.getAsString(detail, "cf_cfmc");
			String cfSy = "处罚事由 : " + GsonUtils.getAsString(detail, "cf_sy");
			String cfJq = "处罚结果 : " + GsonUtils.getAsString(detail, "cf_jq");
			String cfXzjq = "处罚机关 : " + GsonUtils.getAsString(detail, "cf_xzjq");
			String regDate = "更新时间 : " + GsonUtils.getAsString(detail, "reg_date");
			return StringUtils.join(new Object[] { cfWsh, cfCfmc, cfSy, cfJq, cfXzjq, regDate }, " </br> ");
		}
		default:
			log.warn("Does not find any case of reasonCode, value is : {} ", reasonCode);
			return "";
		}
	}
}
